<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <AuTable
      ref="tableRef"
      v-bind="gridOption"
      class="mt-[16px]"
      @actionClick="actionClick"
    >
      <template #topWrap>
        <div class="text-[#242930]">
          <span class="text-[--autata-font-gray-color]"
            >{{ t("formula_detail.version_name") }}：</span
          >
          {{ versionRoute.name }}
        </div>
      </template>
      <template #status_default="{ row }">
        <el-tag :type="row.publish_status === 1 ? 'success' : 'info'"
          >{{
            row.publish_status === 1
              ? t("formulaVersion.statusUp")
              : t("formulaVersion.statusDown")
          }}
        </el-tag>
      </template>
      <template #icon_default="{ row }">
        <el-image :src="row.icon" fit="contain" class="h-[46px]" />
      </template>
    </AuTable>

    <ExcelImport
      v-model="showImportModal"
      :version="versionRoute.id"
      :tableData="tableData"
      @confirm="tableRef?.refresh()"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";

import {
  getformulaDetailList,
  FormulaDetailProp,
  getTagList,
  formulaDelete,
  TagProp,
  formulaGetDetail,
  formulaAdd,
  formulaGetDetailList
} from "@/api/cabinet/formulaDetail";
import { useDetail } from "../hooks";
import { GetListParamProp } from "@/api/user";
import { ElMessage, ElMessageBox, ImageProps } from "element-plus";
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import { useGlobal } from "@pureadmin/utils";
import { VxeGridInstance, VxeGridProps, VxeUI } from "vxe-table";
import { useCabinetStore } from "@/store/modules/cabinet";
import ExcelImport from "./ExcelImport.vue";
import { cloneDeep } from "lodash-unified";
import ExcelJS from "exceljs";
import { saveAs } from "file-saver"; // 引入file-saver, 用于保存文件
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const fits = [
  "fill",
  "contain",
  "cover",
  "none",
  "scale-down"
] as ImageProps["fit"][];

defineOptions({
  name: "CabinetFormulaDetail"
});

const dateValue = ref("");
const size = ref<"default" | "large" | "small">("default");

const emit = defineEmits(["update:showModal"]);
const { initToDetail, getParameter } = useDetail();
initToDetail("query");
const { proxy } = getCurrentInstance();

// region 页面及组件变量集合
const { $storage } = useGlobal<GlobalPropertiesApi>();
const router = useRouter();
const route = useRoute();

const versionRoute = ref({
  id: "",
  name: ""
});
const showUploadModal = ref(false);

const formList = ref([
  {
    type: "el-date-picker",
    key: "sjsj",
    inType: "datetimerange",
    label: "formula_detail.publish_time",
    labelWidth: 68,
    span: 8,
    rangeSeparator: "至",
    startPlaceholder: "formula_detail.start_time",
    endPlaceholder: "formula_detail.end_time",
    valueFormat: "YYYY-MM-DD HH:mm:ss"
  },
  /* {
    type: "input",
    key: "name",
    label: "配方名称",
    placeholder: "请输入配方名称"
  }, */
  {
    type: "select",
    key: "publish_status",
    label: "formula_detail.status",
    placeholder: "formula_detail.status_placeholder",
    labelKey: "label",
    valueKey: "value",
    columns: [],
    options: [
      {
        value: 0,
        label: "formula_detail.status_down"
      },
      {
        value: 1,
        label: "formula_detail.status_up"
      }
    ]
  },
  {
    type: "select",
    multiple: true,
    key: "tag_list",
    label: "formula_detail.tag_list",
    placeholder: "formula_detail.tag_list_placeholder",
    labelKey: "name",
    valueKey: "id",
    columns: [],
    options: []
  }
]);

const showImportModal = ref(false);
const tableData = ref<FormulaDetailProp[]>([]);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  showExportBtn: false,
  columns: [
    { field: "id", title: "formula_detail.id" },
    {
      field: "icon",
      title: "formula_detail.icon",
      slots: { default: "icon_default" }
    },
    { field: "name", title: "formula_detail.name" },
    {
      field: "publish_status",
      title: "formula_detail.status",
      slots: { default: "status_default" }
    },
    { field: "note", title: "table.note" },
    { field: "publish_time", title: "formula_detail.publish_time", width: 190 }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.EDIT, ACTION_TYPE.TDELETE],
  operateTools: [
    {
      key: "copy",
      name: "table.copyFormula"
    }
  ],
  topTools: [
    {
      key: "import",
      name: "table.upload",
      plain: true,
      seq: 12,
      onClick: async () => {
        const res = await formulaGetDetailList({
          size: 0,
          version: versionRoute.value.id
        });
        tableData.value = res.data;
        showImportModal.value = true;
      }
    },
    {
      key: "export",
      name: "table.export",
      seq: 12,
      onClick: () => {
        exportExcel();
      }
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (
        params: GetListParamProp<{ version: string; hxtFormula: object }>
      ) => {
        const { start_page, size, ...rest } = params;
        params = {
          start_page: start_page ?? 1,
          size: size ?? 0,
          ...rest
        };

        return getformulaDetailList(params);
      },
      param: () => {
        const arr = formRef.value.getFormData();
        versionRoute.value = JSON.parse(route.query?.version as string);
        console.log(versionRoute);
        let publishStarttime = null;
        let publishEndtime = null;
        if (arr.sjsj != undefined) {
          publishStarttime = arr.sjsj[0];
          publishEndtime = arr.sjsj[1];
        }
        let tagList = null;

        if (arr.tag_list != undefined && arr.tag_list.length > 0) {
          let temp = [];
          for (let i = 0; i < arr.tag_list.length; i++) {
            console.log(arr.tag_list);
            temp.push({ id: arr.tag_list[i] });
          }
          tagList = JSON.stringify(temp);
        }

        let publishStatus = null;
        if (arr.publish_status != undefined) {
          publishStatus = arr.publish_status;
        }

        return {
          version: versionRoute.value.id,
          publish_starttime: publishStarttime,
          publish_endtime: publishEndtime,
          publish_status: publishStatus,
          tag_list: tagList
        };
      }
    }
  }
});
const rowData = ref({});

const cabinetStore = useCabinetStore();
const formRef = ref();
const tableRef = ref();

// endregion

// region 页面公共方法集合
function storageConfigureChange<T>(key: string, val: T): void {
  const storageConfigure = $storage.configure;
  storageConfigure[key] = val;
  // $storage.configure = storageConfigure;
}

/* const multiDelete = () => {
  if (!tableRef.value.getCheckboxRecords().length) {
    ElMessage({
      message: "请选择要删除的配方",
      type: "warning"
    });
    return;
  }
  proxy.$auMessageBox
    .confirm("是否确认删除该配方？", "提示", {
      type: "error"
    })
    .then(() => {
      const formulaIds = tableRef.value
        .getCheckboxRecords()
        .map((v: FormulaListProp) => v.formulaId);
      delFormula({ formulaIds }).then(res => {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        tableRef.value.refresh();
      });
    });
}; */

const batchCopyData = async (row, name) => {
  const detail = await formulaGetDetail({
    formula_subid: row.formula_subid
  });
  if (detail.data) {
    let data = detail.data;
    let formula_id = data.formula_id;
    let icon = data.icon;
    let tag_list = "";
    if (data.tag_list != null && data.tag_list != "") {
      tag_list = data.tag_list;
    }
    let version = data.version;
    let formula_version = "";
    if (data.formula_version != null && data.formula_version != "") {
      formula_version = data.formula_version;
    }
    let note = data.note;
    let material_list = "";
    if (data.material_list != null && data.material_list) {
      material_list = JSON.stringify(data.material_list);
    }
    let formulaSpecsData = "";
    let formulaSpecificationList = data.specification_list;
    if (formulaSpecificationList != null && formulaSpecificationList) {
      let formulaSpecsDataTemp = [];
      for (let p = 0; p < formulaSpecificationList.length; p++) {
        let formulaSpecsDataObject = {};
        formulaSpecsDataObject["id"] =
          formulaSpecificationList[p].specification_id;
        formulaSpecsDataObject["name"] =
          formulaSpecificationList[p].specification_name;
        formulaSpecsDataObject["attr"] =
          formulaSpecificationList[p].specification_attr;
        formulaSpecsDataObject["check_attr"] =
          formulaSpecificationList[p].check_attr;
        formulaSpecsDataTemp.push(formulaSpecsDataObject);
      }
      formulaSpecsData = JSON.stringify(formulaSpecsDataTemp);
    }
    let formula_detail = data.formula_detail;
    let publish_status = data.publish_status;
    // urlData.append("formula_id", formula_id);
    // urlData.append("icon", icon);
    // urlData.append("name", name);
    // if (tag_list != "") {
    //   urlData.append("tag_list", tag_list);
    // }
    // urlData.append("version", version);
    // urlData.append("formula_version", formula_version);
    // urlData.append("note", note);
    // if (material_list != "") {
    //   urlData.append("material_list", material_list);
    // }
    // if (formulaSpecsData != "") {
    //   urlData.append("specification_list", formulaSpecsData);
    // }
    // urlData.append("formula_detail", JSON.stringify(formula_detail));
    // urlData.append("publish_status", String(publish_status));
    const param = {
      formula_id: formula_id,
      icon: icon,
      name: name,
      tag_list: tag_list,
      version: version,
      formula_version: formula_version,
      note: note,
      material_list: material_list,
      specification_list: formulaSpecsData,
      formula_detail: JSON.stringify(formula_detail),
      publish_status: publish_status
    };
    formulaAdd(param).then(res => {
      ElMessage({
        message: "子配方复制成功",
        type: "success"
      });
      search();
    });
  }
};

const exportExcel = async () => {
  const $table = tableRef.value;
  // const list = $table.vxeGridRef.getTableData().fullData;
  let detailList = [];
  // for (const item of list) {
  //   detailList.push(res.data);
  // }

  const res = await formulaGetDetailList({
    version: versionRoute.value.id,
    size: 0
  });
  detailList = res.data;
  console.log(detailList);

  const exportList = [];
  for (const item of detailList) {
    const cont: ObjectProps = {
      name: item.name,
      third_value: item.third_value
    };
    try {
      const tag = JSON.parse(item.tag_list);
      cont.tag = tag.map(v => v.name).join(",");
    } catch (err) {
      console.error("错误问题：", err);
      cont.tag = "";
    }
    for (const fdItem of item.formula_detail) {
      const copyCont = cloneDeep(cont);
      copyCont.spec = fdItem.materialSpecs?.map(v => v.attr).join("-");
      copyCont.matAmount = fdItem.materialAmount.map(
        v => `${v.material_name}-${v.amount}`
      );
      exportList.push(copyCont);
    }
  }

  console.log(exportList);

  // 获取模板文件
  const path = import.meta.env?.VITE_PUBLIC_PATH;
  const response = await fetch(`/admin/柜式机配方导出模版.xlsx`);
  const arrayBuffer = await response.arrayBuffer();

  // 创建工作簿
  const workbook = new ExcelJS.Workbook();
  await workbook.xlsx.load(arrayBuffer);

  // 获取第一个工作表
  const worksheet = workbook.getWorksheet(1);
  //模板边框样式
  const cellExample = worksheet.getRow(3).getCell(1);
  const cellExampleStyle = {
    top: { ...cellExample.border.top },
    left: { ...cellExample.border.left },
    bottom: { ...cellExample.border.bottom },
    right: { ...cellExample.border.right }
  };
  //模板填充样式
  const cellFillExampleStyle = cellExample.fill;

  for (let i = 2; i < 24; i++) {
    const cell = worksheet.getCell(i, 1);
    cell.fill = cellFillExampleStyle;
  }
  console.log(worksheet);
  for (let i = 0; i < exportList.length; i++) {
    const item = exportList[i];
    worksheet.getRow(2).getCell(i + 2).fill = cellFillExampleStyle;
    worksheet.getColumn(2 + i).width = 20;

    for (let j = 0; j < 24; j++) {
      worksheet.getRow(j + 2).getCell(i + 2).border = cellExampleStyle;
    }

    worksheet.getRow(2).getCell(i + 2).value = i + 1;
    worksheet.getRow(3).getCell(i + 2).value = item.name;
    worksheet.getRow(4).getCell(i + 2).value = item.third_value;
    worksheet.getRow(5).getCell(i + 2).value = item.spec;
    worksheet.getRow(6).getCell(i + 2).value = item.tag;
    for (let j = 0; j < item.matAmount.length; j++) {
      worksheet.getRow(7 + j).getCell(i + 2).value = item.matAmount[j];
    }
  }

  //导出
  workbook.xlsx.writeBuffer().then(function (buffer) {
    // 生成excel文件的二进制数据
    saveAs.saveAs(
      new Blob([buffer], {
        // 生成Blob对象
        type: "application/octet-stream" // 指定文件的MIME类型
      }),
      "配方数据.xlsx"
    ); // 指定文件名
  });
};
// endregion

// region 页面及组件事件集合
const toPrevPage = () => {
  router.push({
    name: "CabinetFormulaManage"
  });
};

const search = () => {
  tableRef.value.refresh();
};

const actionClick = ({
  key,
  row
}: {
  key: ACTION_TYPE | string;
  row: FormulaDetailProp;
}) => {
  switch (key) {
    case ACTION_TYPE.TADD:
      router.push({
        name: "CabinetFormulaDetail",
        query: {
          ...proxy.$route.query
        }
      });
      break;
    case ACTION_TYPE.EDIT:
      router.push({
        name: "CabinetFormulaDetail",
        query: {
          ...proxy.$route.query,
          row: JSON.stringify({
            id: row.id,
            name: row.name,
            formula_subid: row.formula_subid
          })
        }
      });
      break;
    case ACTION_TYPE.TDELETE:
      proxy.$auMessageBox
        .confirm(t("formula_detail.delete_confirm"), t("notice.title"), {
          type: "error"
        })
        .then(() => {
          const checkedNodes = tableRef.value.getCheckboxRecords();
          console.log(checkedNodes);
          if (checkedNodes.length > 0) {
            const ids = checkedNodes.map(item => ({ id: item.id }));
            formulaDelete({
              delList: JSON.stringify(checkedNodes),
              is_auto: true
            }).then(res => {
              if (res.code === 200) {
                VxeUI.modal.message({
                  content: t("notice.operation_success"),
                  status: "success"
                });
                tableRef.value.refresh();
              }
            });
          }
        })
        .catch(() => {});
      break;
    case ACTION_TYPE.VIEW:
      break;
    case "spec":
      router.push({
        name: "CabinetSpecification",
        query: {
          id: row.id,
          name: row.name,
          formula_subid: row.formula_subid
        }
      });
      break;

    case "copy":
      proxy.$auMessageBox
        .prompt(t("formula_detail.copy_confirm"), t("notice.title"), {
          inputValue: `${row.name}_副本`
        })
        .then(res => {
          batchCopyData(row, res.value);
        });
      break;
    default:
      break;
  }
};

const getTagListForSelect = () => {
  const params = {};
  getTagList(params).then(res => {
    console.log("获取tag");
    // formPopList.value[2].options = res.data;
    formRef.value.setFormProps("tag_list", {
      options: res.data,
      hidden: false
    });
  });
};

getTagListForSelect();

cabinetStore.clearState();
// endregion
</script>
